package com.threeskin.weixin;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Dispatcher {
	
	private static final String ACCESS_ERROR = "Error parameter count.";
	
	private static final String ACCESS_FAILED = "Access Failed.";
	
	private static final String TOKEN = "1234567890";
	
	
	@RequestMapping(method=RequestMethod.GET, value="/weixin/access")
	@ResponseBody
	public String accessVerification(
			@RequestParam String signature,
			@RequestParam String timestamp,
			@RequestParam String nonce,
			@RequestParam String echostr
			){
		
		String result = null ;
		
		if (signature == null || timestamp == null || nonce == null
				|| echostr == null) {
			
			result = ACCESS_ERROR ;
			
		} else {
			
			// 1. 将token、timestamp、nonce三个参数进行字典序排序 
			String[] strArr = new String[] { TOKEN, timestamp, nonce };
			java.util.Arrays.sort(strArr);
			
			// 2. 将三个参数字符串拼接成一个字符串  
			StringBuffer sb = new StringBuffer();  
		    for (String str : strArr)  
		    {  
		        sb.append(str);  
		    } 
		    
		    // 3. 进行sha1加密
		    MessageDigest mdSha1 = null;
		    
		    try  
		    {  
		        mdSha1 = MessageDigest.getInstance("SHA-1");  
		    }  
		    catch (NoSuchAlgorithmException e)  
		    {  
		        e.printStackTrace();  
		    }
		    
		    mdSha1.update(sb.toString().getBytes());  
		    
		    byte[] codedBytes = mdSha1.digest(); 
		    
		    String codedString = new BigInteger(1, codedBytes).toString(16);
		    
		    //4. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		    if (codedString.equals(signature)) {
		    	result = echostr ;
		    }else{
		    	result = ACCESS_FAILED ;
		    }
		}
		
		return result ;
	}

}
